package com.example.demo.service.impl;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

public class ImageCodeUtils {
	//1.生成随机数
	private String[] arr= {"1","2","3","a","b","c","6","v","q"};
	//2.生成随机数
	public String createCode(int n ,HttpSession httpSession) {
		StringBuilder sb =new StringBuilder("");
		Random rn =new Random();
		for(int i=0;i<n;i++) {
			int p =rn.nextInt(arr.length);
			sb.append(arr[p]);
		}
		httpSession.setAttribute("code",sb.toString());
		return sb.toString();
	}
	
	public InputStream createImage(String code) {
		BufferedImage bi = new BufferedImage(80, 40,BufferedImage.TYPE_INT_RGB);
		Graphics g =bi.getGraphics();
		g.setColor(Color.gray);
		g.fillRect(0, 0, 100, 30);
		for (int i = 0; i < code.length(); i++) {
			g.setColor(Color.yellow);
			String ch =code.charAt(i)+"";
			g.drawString(ch, 20*i+5, 20);
		}
		//
		ByteArrayOutputStream out =new ByteArrayOutputStream();
		try {
			ImageIO.write(bi, "jpg", out);
			ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
			return in;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
		
	}
	public static void main(String[] args ,HttpSession httpSession) {
		ImageCodeUtils is =new ImageCodeUtils();
		System.out.println(is.createCode(2,httpSession));
	}

}
